<template>
  <div>
    <form action="/">
      <van-search
        v-model.trim="keywords"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        background="rgb(50, 150, 250)"
        class="search-ipt"
        @focus="isShowResult = false"
      />
    </form>
    <component
      :keywords="keywords"
      :is="componentName"
      @update-keywords="onSearch"
    ></component>
  </div>
</template>

<script>
import SearchHistory from './components/SearchHistory.vue'
import SearchResult from './components/SearchResult.vue'
import SearchSuggestions from './components/SearchSuggestions.vue'
import { mapState, mapMutations } from 'vuex'
export default {
  name: '',
  components: { SearchSuggestions, SearchHistory, SearchResult },
  props: {},
  data() {
    return {
      keywords: '',
      isShowResult: false
    }
  },
  computed: {
    ...mapState(['histories']),
    componentName() {
      if (this.keywords === '') {
        return 'SearchHistory'
      }
      if (this.isShowResult) {
        return 'SearchResult'
      }
      return 'SearchSuggestions'
    }
  },
  watch: {},
  created() {},
  methods: {
    ...mapMutations(['SET_HISTORIES']),
    onSearch(val) {
      this.keywords = val
      let newHistories = [this.keywords, ...this.histories]
      newHistories = [...new Set(newHistories)]
      this.SET_HISTORIES(newHistories)
      this.isShowResult = true
    },
    onCancel() {
      // 由于vant组件该事件会先进行清除在执行代码，所以一直都是跳转页面
      if (this.keywords === '') {
        this.$router.go(-1)
      } else {
        this.keywords = ''
      }
    }
  }
}
</script>

<style scoped lang="less">
.search-ipt {
  .van-search__action {
    color: #fff;
  }
}
</style>
